package com.das.mechanic_base.widget;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.adapter.camera.X3CameraPhotoAdapter;
import com.das.mechanic_base.app.X3AppRouterConstants;
import com.das.mechanic_base.app.X3RouterCenter;
import com.das.mechanic_base.base.X3BaseBottomSheetDialog;
import com.das.mechanic_base.base.X3IBaseView;
import com.das.mechanic_base.bean.alone.AloneImageAndRecordBean;
import com.das.mechanic_base.bean.camera.ImageVideoBean;
import com.das.mechanic_base.bean.custrecord.DetectionImageBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.umeng.analytics.MobclickAgent;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class X3BottomAloneImageNumDialog extends X3BaseBottomSheetDialog implements View.OnClickListener, X3CameraPhotoAdapter.ItemCallback {

    TextView tv_title;
    RecyclerView rlv_alone;
    TextView tv_cancel;
    Button btn_create;
    SmartRefreshLayout sl_view;

    private X3CameraPhotoAdapter photoAdapter;

    private List<AloneImageAndRecordBean> pathList = new ArrayList<>();

    private int allNum;

    private long id;

    private boolean isAlone;

    private int bodyIndex = 1;
    private int imageIndex;
    private int titleIndex;
    private  List<AloneImageAndRecordBean> imgList;
    private List<String> selectList;
    private boolean isWork;

    public X3BottomAloneImageNumDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected boolean getDialogCancel() {
        return false;
    }

    @Override
    protected void initView() {
        rlv_alone = getView(R.id.rlv_alone);
        tv_title = getView(R.id.tv_title);
        tv_cancel = getView(R.id.tv_cancel);
        btn_create = getView(R.id.btn_create);
        sl_view = getView(R.id.sl_view);

        tv_cancel.setOnClickListener(this);
        btn_create.setOnClickListener(this);

        rlv_alone.setLayoutManager(new GridLayoutManager(mContext, 3));
        photoAdapter = new X3CameraPhotoAdapter(mContext, this,rlv_alone);
        rlv_alone.setAdapter(photoAdapter);

        sl_view.setEnableRefresh(false);
        sl_view.setEnableHeaderTranslationContent(false);
        sl_view.setEnableLoadMore(true);
        sl_view.setOnLoadMoreListener(refreshLayout -> {
            sl_view.finishLoadMore(500);
            this.bodyIndex++;
            getImageFromHttp();
        });

        sl_view.setOnRefreshListener(refreshlayout -> {
            sl_view.finishRefresh(500);
            this.bodyIndex = 1;
            getImageFromHttp();
        });
    }

    /**
     * 从检测或者施工报告中获取图片
     * @param allNum
     * @param id
     * @param isAlone
     */
    public void getImageList(int allNum,long id,boolean isAlone,String title,int titleIndex,int imageIndex,List<AloneImageAndRecordBean> imgList,boolean isWork) {
        this.allNum = allNum;
        this.id = id;
        this.isAlone = isAlone;
        this.isWork = isWork;
        this.bodyIndex = 1;
        this.imageIndex = imageIndex;
        this.titleIndex = titleIndex;
        this.imgList = imgList;
        tv_title.setText(isAlone ? title : mContext.getString(R.string.work_images));
        getImageFromHttp();
    }

    private void getImageFromHttp() {
        if (isAlone) {
            requestFromDetection();
        }else {
            requestFromWork();
        }
    }

    private void requestFromWork() {
        Map<String,Object> map = new HashMap<>();
        map.put("pageNum",bodyIndex);
        map.put("pageSize",20);
        map.put("id",id);

        NetWorkHttp.getApi().getResourceListFromWorkProcedure(map)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(((X3IBaseView)mContext).bindToLife())
                .subscribe(new HttpCallBack<DetectionImageBean>() {
                    @Override
                    protected void onDone(DetectionImageBean detectionImageBeans) {
                        showImage(detectionImageBeans);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    private void requestFromDetection() {
        Map<String,Object> map = new HashMap<>();
        map.put("pageNum",bodyIndex);
        map.put("pageSize",20);
        map.put("id",id);

        NetWorkHttp.getApi().getResourceListFromDetection(map)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(((X3IBaseView)mContext).bindToLife())
                .subscribe(new HttpCallBack<DetectionImageBean>() {
                    @Override
                    protected void onDone(DetectionImageBean detectionImageBeans) {
                        showImage(detectionImageBeans);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });

    }

    /**
     * 展示图片
     * @param imageBean
     */
    private void showImage(DetectionImageBean imageBean) {
        if (imageBean == null) {
            return;
        }
        List<DetectionImageBean.ListBean> aList = imageBean.list;
        if (X3StringUtils.isListEmpty(aList)) {
            return;
        }
        if (photoAdapter == null) {
            return;
        }
        List<ImageVideoBean> mList = new ArrayList<>();

        if (bodyIndex == 1) {
            for (int i = 0; i < aList.size(); i++) {
                mList.add(new ImageVideoBean(X3StringUtils.getImageUrl(aList.get(i).value),aList.get(i).key,0));
            }
            photoAdapter.setData(mList);
        }else {
            if(bodyIndex <= imageBean.pages){
                for (int i = 0; i < aList.size(); i++) {
                    mList.add(new ImageVideoBean(X3StringUtils.getImageUrl(aList.get(i).value),aList.get(i).key,0));
                }
            }
            photoAdapter.addData(mList);
        }

        selectList = new ArrayList<>();
        for (int i = 0; i < imgList.size(); i++){
            selectList.add(X3StringUtils.getImageUrl(imgList.get(i).getHttpPath()));
        }
        photoAdapter.setDefaultSelected(selectList);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_bottom_alone_image_num_dialog;
    }

    @Override
    public void onClick(View v) {
        int vId = v.getId();
        if (vId == R.id.tv_cancel) {
            dismiss();
        } else if (vId == R.id.btn_create) {
            if (X3StringUtils.isListEmpty(pathList)) {
                return;
            }
            dismiss();
            if (iOnSelectImage != null) {
                iOnSelectImage.iOnSelectImage(pathList, titleIndex, imageIndex,isWork);
            }
        }
    }

    IOnSelectImage iOnSelectImage;

    public void setiOnSelectImage(IOnSelectImage iOnSelectImage) {
        this.iOnSelectImage = iOnSelectImage;
    }

    public interface IOnSelectImage {
        void iOnSelectImage(List<AloneImageAndRecordBean> pathList,int titleIndex,int imageIndex,boolean isWork);
        void iOnRemoveImage(AloneImageAndRecordBean  aloneImageAndRecordBean,int titleIndex,int imageIndex,boolean isWork);
    }

    @Override
    public void show() {
        super.show();
        if (photoAdapter != null) {
            photoAdapter.clearSelectImages();
            pathList.clear();
        }
        changeButtonStatus(false);
    }

    @Override
    public void iOnCameraShow(int position) {
        ImageVideoBean image = photoAdapter.getItem(position);
        if (image == null) {
            return;
        }
        if (photoAdapter.getmSelectedImages().contains(image) && selectList.contains(image.path)) {
//            return;
            //数据库删除
            if(iOnSelectImage != null){
                iOnSelectImage.iOnRemoveImage(new AloneImageAndRecordBean(image.path,image.path, (int) image.addTime,1) ,titleIndex,imageIndex,isWork);
            }
            allNum++;
            image = null;

        }

        int haveIndex = -1;

        for (int i = 0; i < pathList.size(); i++) {
            AloneImageAndRecordBean imageAndRecordBean = pathList.get(i);
            if (image!=null && image.path.equals(imageAndRecordBean.getPath())) {
                haveIndex = i;
                break;
            }
        }
        if (haveIndex != -1) {
            pathList.remove(haveIndex);
        } else {
            // 判断选择数量问题
            if (allNum == pathList.size()) {
                X3ToastUtils.showMessage(String.format(mContext.getString(R.string.x3_picture_max_nine),allNum));
                return;
            }
            if(image != null){
                pathList.add(new AloneImageAndRecordBean(image.path,image.path, (int) image.addTime,1));
            }

        }
        photoAdapter.select(position);
        if (X3StringUtils.isListEmpty(pathList)) {
            changeButtonStatus(false);
            return;
        }
        if(pathList.size() > 0 ){
            changeButtonStatus(true);
        }else {
            changeButtonStatus(false);
        }

    }

    @Override
    public void iOnCameraSelectShow(String path,boolean isFirst) {
        if (isFirst) {
            return;
        }
        List<String> mList = new ArrayList<>();
        mList.add(path);
        Bundle bundle = new Bundle();
        bundle.putSerializable("imageList", (Serializable) mList);
        bundle.putInt("index",0);
        X3RouterCenter.startNavigate(X3AppRouterConstants.Router.SHOW_IMAGE,bundle);
    }

    private void changeButtonStatus(boolean isEnable) {
        btn_create.setTag(isEnable);
        btn_create.setBackground(isEnable ? ContextCompat.getDrawable(getContext(),R.drawable.x3_alone_dialog_affirm) : ContextCompat.getDrawable(getContext(),R.drawable.x3_shape_rad_4_cor_d5d5));
    }

    @Override
    protected void onStart() {
        super.onStart();
        MobclickAgent.onPageStart("施工工艺施工报告图库弹窗");
    }

    @Override
    protected void onStop() {
        super.onStop();
        MobclickAgent.onPageEnd("施工工艺施工报告图库弹窗");
    }
}
